-- UISkyCityExploreShopGoodsInfo
-- Create by chendh
-- 天空探索特殊商店商品信息界面

-- UISkyCityExploreShopGoodsInfo继承自Layer
UISkyCityExploreShopGoodsInfo = class("UISkyCityExploreShopGoodsInfo", function()
    return cc.Layer:create();
end);

function UISkyCityExploreShopGoodsInfo.create(exploreIndex, goodsIndex)
    return UISkyCityExploreShopGoodsInfo.new(exploreIndex, goodsIndex);
end

-- 构造函数
function UISkyCityExploreShopGoodsInfo:ctor(exploreIndex, goodsIndex)
    self:setName("UISkyCityExploreShopGoodsInfo");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/shop/BlackMarketGoodsDetail.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 记录商品信息
    self.exploreIndex = exploreIndex;
    local skyExplore = ME.user.dbase:query("sky_explore", {});
    local exploreInfo = skyExplore[exploreIndex];
    self.exploreInfo = exploreInfo;
    self.goodsIndex = goodsIndex;
    self.goodsId = exploreInfo["goods"][goodsIndex];

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 注册事件处理回调函数
function UISkyCityExploreShopGoodsInfo:registerEventCallback()

end

-- 注册点击事件
function UISkyCityExploreShopGoodsInfo:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("ship_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyCityExploreShopGoodsInfo");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册确认购买按钮点击事件
    local btnBuy = findChildByName(self.node, "CT/btn_buy");
    local function onBuyClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 尝试购买
            self:tryBuy();
        end
    end
    btnBuy:addTouchEventListener(onBuyClick);
    TextStyleM.setTextStyle(btnBuy, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBuy:setTitleText(getLocStr("confirm_to_buy"));
end

-- 重绘
function UISkyCityExploreShopGoodsInfo:redraw()
    -- 显示商品名称
    local CT = findChildByName(self.node, "CT");
    local nameLabel = CT:getChildByName("name");
    local goodsInfo = SkyExploreShopM.query(self.goodsId);
    local goods = goodsInfo["goods"];

    local goodNum = goods[3];
    local classId = goods[2];
    local goodsType = goods[1];
    local itemInfo = ItemM.query(classId);

    local nameDesc;
    if goodNum > 1 then
        nameDesc = string.format(getLocStr("item_bonus_format"), itemInfo["name"], goodNum);
    else
        nameDesc = string.format(getLocStr("have_took_boss_gift"), itemInfo["name"]);
    end

    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
    nameLabel:setString(nameDesc);

    -- 显示商品描述
    local desc;
    if goodsType == 1 then
        desc = ItemM.getItemDesc(classId);
    elseif goodsType == ROBOT then
        desc = SkyRobotM.query(classId, "desc");
    else
        desc = SkyShipSkillM.getShipSkillDesc(classId);
    end

    -- 需求此处普通道具不显示细节描述了
    local detail = "";

    if goodsType == 1 and itemInfo.type == ITEM_TYPE_DEVICE_MATERIAL then
        detail = "[blue]" .. itemInfo.detail .. "[-]\n\n";
    end

    local descLabel = CT:getChildByName("desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    descLabel = applyString(descLabel, desc);

    local detailLabel = CT:getChildByName("detail");
    TextStyleM.setTextStyle(detailLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    detailLabel = applyString(detailLabel, detail);

    -- 显示商品价格
    local price = goodsInfo["price"];
    local payAttrib    = price[2];
    local priceAmount  = price[3];
    local ownAmount;
    local fieldName;
    local attribDesc;

    if 2 == price[1] then
        ownAmount    = ME.user:queryAttrib(payAttrib);
        fieldName    = FieldsM.getFieldName(payAttrib);
        attribDesc   = string.format(getLocStr("attrib_value_format"), ownAmount, priceAmount);
        if priceAmount > ownAmount then
            attribDesc = "[red]" .. attribDesc .. "[-]";
        end
    else
        ownAmount    = ItemM.getAmount(ME.user, payAttrib);
        fieldName    = ItemM.query(payAttrib, "name");
        attribDesc   = string.format(getLocStr("attrib_value_format"), ownAmount, priceAmount);

        if priceAmount > ownAmount then
            attribDesc = "[red]" .. attribDesc .. "[-]";
        end
    end
    local costDesc = string.format(getLocStr("buy_cost_attrib2"), fieldName, attribDesc);

    costDesc = costDesc .. "\n";

    -- 显示拥有商品数量
    local amountLabel = CT:getChildByName("own_amount");
    TextStyleM.setTextStyle(amountLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GREEN);

    if goodsType == 1 then
        local amount = ItemM.getOwnedAmount(ME.user, classId);
        costDesc = costDesc .. string.format(getLocStr("own_goods_amount2"), amount);
        amountLabel = applyString(amountLabel, costDesc);
    else
        amountLabel = applyString(amountLabel, costDesc);
    end

    -- 自适应所有组件
    local bg = findChildByName(self.node, "CT/bg");
    local btnBuy = findChildByName(self.node, "CT/btn_buy");
    AlignM.adaptLayout(bg, AlignM.BG_SIZE_NORMAL,
        { nameLabel, descLabel, detailLabel, amountLabel, btnBuy});

    -- 显示商品阶位
    local rank = 0;

    if goodsType == ROBOT then
        rank = SkyRobotM.query(classId, "rank") or 0;
    elseif goodsType ~= TREASURE then
        rank = ItemM.query(classId, "rank") or 0;
    end

    if rank > 0 then
        local needShow = false;
        if goodsType == ROBOT then
            needShow = true;
        else
            needShow = FormulaM.invoke("NEED_SHOW_STAR", classId);
        end
        if needShow then
            local starNode = findChildByName(self.node, "CT/star_node");
            local layer = createStarLayer(rank, "images/ui/symbol/star_large.png", "right");
            if layer then
                starNode:removeAllChildren();
                starNode:addChild(layer);
            end
            starNode:setPositionY(nameLabel:getPositionY());
        end
    end
end

-- 适配
function UISkyCityExploreShopGoodsInfo:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 尝试购买
function UISkyCityExploreShopGoodsInfo:tryBuy()
    -- 判断能否购买
    local ret = SkyExploreShopM.canBuyGoods(self.exploreIndex, self.goodsIndex);
    if ret ~= true then
        AudioM.playFx("market_buy_failed");
        if ret == "sold_out" then
            -- 商品已售完
            alert(getLocStr("goods_sold_out"));
        elseif string.endWith(ret, "_lack") then
            -- 属性不足
            local field = string.sub(ret, 1, -6);
            if field == "gem" then
                showGemLackConfirm();
            else
                local fieldName;
                if string.startWith(field, "item_") then
                    local classId = tonumber(string.sub(field, 6, -1));
                    fieldName = ItemM.query(classId, "name");
                else
                    fieldName = FieldsM.getFieldName(field);
                end

                local msg = string.format(getLocStr("fail_to_do_operate"), fieldName, getLocStr("buy"));
                alert(msg);
            end
        else
            -- 未知原因
            cclog("购买商品失败，原因：" .. ret );
        end
        -- 关闭当前界面
        UIMgr.getCurrentScene():removeFormByName("UISkyCityExploreShopGoodsInfo");
        return;
    end

    -- 执行购买
    AudioM.playFx("market_buy_success");
    SkyExploreShopM.buyGoods(self.exploreIndex, self.goodsIndex);

    -- 关闭当前界面
    UIMgr.getCurrentScene():removeFormByName("UISkyCityExploreShopGoodsInfo");
end

